'use strict';
// 需要先执行初始化 npm init -y 生成packages.json文件后
// 再执行安装 npm install sha1
// 安装在当前目录哦。。不是全局安装的
const sha1 = require("sha1");
const FormData = require("form-data");
const token = "123qweASD";
const db = uniCloud.database();

function verifyMSGSender(params) {
	const mysignature = sha1([token, params.timestamp, params.nonce].sort().join(""));

	console.log(mysignature === params.signature ? "校验通过" : "校验失败");

	if (mysignature === params.signature) return true;
	else return false;
}

async function uploadTempImg(img_url, access_token){
	// 现将图片链接转为buffer
	const url = await uniCloud.httpclient.request(img_url)
	let buff = new Buffer(url.data);
	// 此处的FormData需要安装到当前云函数文件夹中
	// npm install form-data
	let form = new FormData()
	// 将 media 参数、buff信息、formdata中需要包含的filename、图片信息打包
	form.append('media', buff, {
		filename: `${Date.now()}.jpg`,
		contentType: 'image/jpeg'
	})
	// 请求微信服务器API，将formdata信息上传，获取到media_id
	const imgRes = await uniCloud.httpclient.request(
		"https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + '&type=image', {
			method: "POST",
			headers: form.getHeaders(),
			dataType: 'json',
			content: form.getBuffer()
		});
		return imgRes.data.media_id
}

exports.main = async (event, context) => {
	// 获取config中配置的appid和appSecret
	let appId = await db.collection('wx_config').where({
		'key': 'wxId'
	}).get()
	let appSecret = await db.collection('wx_config').where({
		'key': 'wxSecret'
	}).get()
	const APPID = appId.data[0].val
	const APPSECRET = appSecret.data[0].val
	const tokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + APPID + '&secret=' + APPSECRET;
	// uniCloud.httpclient 发起请求
	const res1 = await uniCloud.httpclient.request(tokenUrl,
	{
		method: 'GET',
		dataType:"json"
	});
	//返回数据给客户端
	const access_token = res1.data.access_token;

	//event为客户端上传的参数
	if (!verifyMSGSender(event.queryStringParameters)) return "来源校验失败";
	//校验通过后，下面这行返回echostr的代码注释掉
	// else return event.queryStringParameters.echostr;

	// 解析json格式字符串
	const receiveMsg = JSON.parse(event.body);
	const url = 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-a8a16cef-f2b9-4644-b216-3b95bcb12602/eed2e97a-be28-4e6d-beb3-ca338d195858.jpg'
	// 判断用户发送的消息内容
	if(receiveMsg.Content === '2'){
		// 调用获取media_id的方法
		// 因为方法是一个promise，所以调用的时候需要加上 await 前缀
		let media_id = await uploadTempImg(url, access_token)
		if(media_id){
			// 发送消息
			const res2 = await uniCloud.httpclient.request(
				"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + access_token, {
					method: "POST",
					headers: {
						"Content-Type": "application/json"
					},
					dataType: "json",
					data: {
						touser: receiveMsg.FromUserName, //接收此消息用户的openid
						msgtype: "image", //此消息的类型
						image: {
							media_id: media_id
						}
					}
				});
		}
	}
	
	const url1 = 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-a8a16cef-f2b9-4644-b216-3b95bcb12602/b30b232d-00f9-4be7-a788-5ff50faf14ca.jpeg'
	// 判断用户发送的消息内容
	if(receiveMsg.Content === '66'){
		// 调用获取media_id的方法
		// 因为方法是一个promise，所以调用的时候需要加上 await 前缀
		let media_id = await uploadTempImg(url1, access_token)
		if(media_id){
			// 发送消息
			const res2 = await uniCloud.httpclient.request(
				"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + access_token, {
					method: "POST",
					headers: {
						"Content-Type": "application/json"
					},
					dataType: "json",
					data: {
						touser: receiveMsg.FromUserName, //接收此消息用户的openid
						msgtype: "image", //此消息的类型
						image: {
							media_id: media_id
						}
					}
				});
		}
	}

	//返回数据给客户端
	return;
};
